package com.pengshun.modules.security;

import com.pengshun.modules.api.mapper.PsUserInfoMapper;
import com.pengshun.modules.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;


@Component
public class SelfUserDetailsService implements UserDetailsService {

    @Autowired  //业务服务类
    private PsUserInfoMapper psUserInfoMapper;

//    @Autowired
//    private PermissionPermissionMapper ppm;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = psUserInfoMapper.findUserByPhone(userName);
        if (user != null) {
//            List<PermissionPermission> permissions = ppm.findByAdminUserId(user.getType());
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
//            for (PermissionPermission item : permissions) {
//                if (item != null && item.getPermission()!=null) {
//
//                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(item.getPermission());
//                    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
//                    grantedAuthorities.add(grantedAuthority);
//                }
//            }
            return new SelfUserDetails(user.getPhone(), user.getPassword(), grantedAuthorities,user.getEnabled());
        } else {
            throw new UsernameNotFoundException("账号不存在!");
        }
    }

}
